package com.generator.mybatisplus;

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.LoadState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class ABx {


    private static final String[] CHINESE_DIGITS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    private static final String[] CHINESE_UNITS = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千"};
    private static final String[] WEEK = {"星期", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"};

    /**
     * 数字转换为汉字大写
     * @param number
     * @return
     */
    public static String convertChinese(Long number) {
        if (number == null) {
            return CHINESE_DIGITS[0];
        }
        if (number == 0) {
            return CHINESE_DIGITS[0];
        }
//        if (number < 0 || number >= 100000) {
//            return number.toString();
//        }
        StringBuilder result = new StringBuilder();
        int unitIndex = 0;
        while (number > 0) {
            int digit = (int)( number % 10);
            if (digit != 0) {
                result.insert(0, CHINESE_UNITS[unitIndex]);
                result.insert(0, CHINESE_DIGITS[digit]);
            } else if (result.length() > 0 && result.charAt(0) != '零') {
                result.insert(0, CHINESE_UNITS[unitIndex]);
            }
            number /= 10;
            unitIndex++;
        }
        return result.toString();
    }

    @Test
    public void cc () {
        System.out.println(convertChinese(2001111111l));
        System.out.println(convertChinese(13401000l));
    }

    /**
     * 获取公网ip
     */
    @Test
    public void cds() {
        try {
            String path = "http://www.net.cn/static/customercare/yourip.asp";// 要获得html页面内容的地址

            URL url = new URL(path);// 创建url对象

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 打开连接

            conn.setRequestProperty("contentType", "GBK"); // 设置url中文参数编码

            conn.setConnectTimeout(5 * 1000);// 请求的时间

            conn.setRequestMethod("GET");// 请求方式

            InputStream inStream = conn.getInputStream();
            // readLesoSysXML(inStream);

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    inStream, "GBK"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            // 读取获取到内容的最后一行,写入
            while ((line = in.readLine()) != null) {
                buffer.append(line);
            }
            List<String> ips = new ArrayList<String>();

            //用正则表达式提取String字符串中的IP地址
            String regEx="((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
            String str = buffer.toString();
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(str);
            while (m.find()) {
                String result = m.group();
                ips.add(result);
            }
            String PublicIp = ips.get(0);

            // 返回公网IP值
            System.out.println("ipd: " + PublicIp);

        } catch (Exception e) {
            System.out.println("获取公网IP连接超时");

        }

    }
    @Test
    public void threadCs () {
        int CPU_COUNT = Runtime.getRuntime().availableProcessors();
        System.out.println(CPU_COUNT);
        System.out.println(Math.max(2, Math.min(CPU_COUNT - 1, 4)));
        //

        System.out.println(Long.parseLong("10101", 2));
        System.out.println("11".concat("_").concat(""));
    }


    @Test
    public void urlToPdf () {
        //可以使用的
        String url = "http://192.168.0.152:38083/pdfreport/#/index?semesterId=1838421263363993600&studentId=1588002049009975296";
        String outputPath = "d:/home/学期报告.pdf";
        generateHtmlToPdf(url, outputPath, null);
    }

    public static String generateHtmlToPdf(String url, String fileName, OutputStream outputStream) {
        /*
        https://blog.csdn.net/Dreamfly527/article/details/144696066 参考文档
         */
        log.info("开始生成网页的 pdf 文件，url={}",url);
        try {
            Playwright playwright = Playwright.create();
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();
            //new Browser.NewContextOptions()
            //                    .setViewportSize(375, 667) // 设置模拟 iPhone 6/7/8 的视口
            //                    .setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1")
            Page page = context.newPage();
            page.navigate(url);
            // 修改根节点 <html> 的 font-size，设置为 16px（这是 1rem 对应的大小）
            page.evaluate("document.documentElement.style.fontSize = '25px';");
            //等待加载完成后
            page.waitForLoadState(LoadState.NETWORKIDLE);
            // 等待字体加载（如果页面依赖于 Web 字体）
            page.evaluate("document.fonts.ready.then(() => { window.isFontLoaded = true; });");
            page.waitForFunction("window.isFontLoaded === true");
            //手动等待 10秒
            page.waitForTimeout(10000);
            // 设置视口大小
            //page.setViewportSize(1920, 1080); // 设置视口大小为 1920x1080
            // 临时文件路径
            if (StringUtils.isEmpty(fileName)){
                fileName = "webPage.pdf";
            }
            //fileName = "d:/home/"+fileName;
            //fileName =" /Users/macbook/Project/logs/manage/"+fileName;
            File tempFile = new File(fileName);
            if (tempFile == null || !tempFile.exists()){
                //tempFile.createNewFile();
            }
            // 输出为 PDF
            page.pdf(new Page.PdfOptions()
                            .setPath(Paths.get(tempFile.getAbsolutePath()))  // 设置输出 PDF 的路径
                            .setFormat("A4")  // 设置纸张格式
                            .setPrintBackground(true)  // 确保背景和图像被打印
                    //.setMargin(new Margin().setTop("10px").setBottom("10px").setLeft("10px").setRight("10px"))  // 设置边距
            );
            //输出到流
            if (outputStream != null){
                try {
                    byte[] pdfData = Files.readAllBytes(tempFile.toPath());
                    outputStream.write(pdfData);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            // 删除临时文件
            //tempFile.delete();

            // 获取网页加载后的 HTML
            //content = page.content();
            browser.close();
        }catch (Exception e) {
            log.info("错误:{}", e);
            return fileName;
        }
        log.info("完成生成网页的 pdf 文件");
        return fileName;
    }

}
